package com.eightbears.beboy.base.util;

import android.app.Activity;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.ColorStateList;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.net.Uri;
import android.provider.Settings;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.util.Base64;
import android.view.View;
import android.widget.ImageView;

import com.amap.api.maps.model.LatLng;
import com.eightbears.beboy.R;
import com.eightbears.beboy.base.view.picker.utils.DateUtils;
import com.eightbears.beboy.base.view.popupwindow.BottomSelectionPopup;
import com.eightbears.beboy.entity.LocationEntity;
import com.makeramen.roundedimageview.RoundedTransformationBuilder;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Transformation;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

import org.json.JSONArray;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Method;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.eightbears.beboy.base.util.CommonAPI.PACKAGE_NAME_AMAP;
import static com.eightbears.beboy.base.util.CommonAPI.PACKAGE_NAME_BAIDU;

/**
 * Created by baoga on 2017/7/3.
 */
public class CommonUtils {

    public static String zYear = "";
    public static String zMonth = "";
    public static String zDay = "";
    public static float scale = 0.2f;
    private static Bitmap bitmapCover;

    /**
     * 加载图片
     */
    public static void loadImageView(Context mContext, String path, int holderImg, ImageView mImageView) {
        Transformation transformation = new RoundedTransformationBuilder()
                .borderColor(ColorStateList.valueOf(mContext.getResources().getColor(R.color.transparent_99FFF)))
                .borderWidth(2)
                .oval(false)
                .build();
        if (TextUtils.isEmpty(path)) {
            path = holderImg + "";
        }
        Picasso.with(mContext).load(path)
                .fit().transform(transformation).centerCrop()
                .placeholder(holderImg)
                .error(holderImg)
                .into(mImageView);
    }

    /**
     * 加载图片
     */
    public static void loadImageView(Context mContext, File path, int holderImg, ImageView mImageView) {
        Transformation transformation = new RoundedTransformationBuilder()
                .borderColor(ColorStateList.valueOf(mContext.getResources().getColor(R.color.transparent_99FFF)))
                .borderWidth(2)
                .oval(false)
                .build();

        Picasso.with(mContext).load(path)
                .fit().transform(transformation).centerCrop()
                .placeholder(holderImg)
                .error(holderImg)
                .into(mImageView);
    }

    //获取是否存在NavigationBar
    public static boolean checkDeviceHasNavigationBar(Context context) {
        boolean hasNavigationBar = false;
        Resources rs = context.getResources();
        int id = rs.getIdentifier("config_showNavigationBar", "bool", "android");
        if (id > 0) {
            hasNavigationBar = rs.getBoolean(id);
        }
        try {
            Class systemPropertiesClass = Class.forName("android.os.SystemProperties");
            Method m = systemPropertiesClass.getMethod("get", String.class);
            String navBarOverride = (String) m.invoke(systemPropertiesClass, "qemu.hw.mainkeys");
            if ("1".equals(navBarOverride)) {
                hasNavigationBar = false;
            } else if ("0".equals(navBarOverride)) {
                hasNavigationBar = true;
            }
        } catch (Exception e) {

        }
        return hasNavigationBar;

    }

    /**
     * 获取手机唯一标示
     */
    public static String getAndroidId(Context context) {
        return Settings.System.getString(context.getContentResolver(), Settings.System.ANDROID_ID);
    }

    /**
     * 将Object序列变化
     */
    public static String obj2Str(Object obj) throws IOException {
        if (obj == null) {
            return "";
        }
        // 实例化一个ByteArrayOutputStream对象，用来装载压缩后的字节文�?
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        // 然后将得到的字符数据装载到ObjectOutputStream
        ObjectOutputStream oos = new ObjectOutputStream(baos);
        // writeObject 方法负责写入特定类的对象的状态，以便相应的readObject可以还原�?
        oos.writeObject(obj);
        // 用Base64.encode将字节文件转换成Base64编码，并以String形式保存
        String listString = new String(Base64.encode(baos.toByteArray(), Base64.DEFAULT));
        // 关闭oos
        oos.close();
        return listString;
    }

    /**
     * 将序列化的数据还原成Object
     */
    public static Object str2Obj(String str) throws IOException {
        if (str != null && !str.equals("")) {
            byte[] mByte = Base64.decode(str.getBytes(), Base64.DEFAULT);
            ByteArrayInputStream bais = new ByteArrayInputStream(mByte);
            ObjectInputStream ois = new ObjectInputStream(bais);

            try {
                return ois.readObject();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 将时间戳转换为指定的格式化日期
     */
    public static String TimeStamp2Date(String timestampString, String formats) {
        Long timestamp = Long.parseLong(timestampString) * 1000;
        String date = new SimpleDateFormat(formats).format(new Date(timestamp));
        return date;
    }


    public static String Date2TimeStamp(String dateString, String formats) {
        SimpleDateFormat sdr = new SimpleDateFormat(formats, Locale.CHINA);
        Date date;
        String times = null;
        try {
            date = sdr.parse(dateString);
            long l = date.getTime();
            String stf = String.valueOf(l);
            times = stf.substring(0, 10);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return times;
    }

    public static String dateToStamp(String s) throws ParseException {
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Date date = simpleDateFormat.parse(s);
        long ts = date.getTime();
        res = String.valueOf(ts / 1000);
        return res;
    }

    public static String dateToStamp(String s, String fomat) {
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(fomat);
        try {
            Date date = simpleDateFormat.parse(s);
            long ts = date.getTime();
            res = String.valueOf(ts / 1000);
            return res;
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return null;
    }

    public static String getStartTimeOfDay() {
        TimeZone curTimeZone = TimeZone.getTimeZone("GMT+8");
        Calendar calendar = Calendar.getInstance(curTimeZone);
        calendar.setTimeInMillis(System.currentTimeMillis());
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        return calendar.getTimeInMillis() / 1000 + "";
    }

    public static String getEndTimeOfDay() {
        TimeZone curTimeZone = TimeZone.getTimeZone("GMT+8");
        Calendar calendar = Calendar.getInstance(curTimeZone);
        calendar.setTimeInMillis(System.currentTimeMillis());
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        return calendar.getTimeInMillis() / 1000 + "";
    }

    public static String getStartTimeOfMonth() {
        TimeZone curTimeZone = TimeZone.getTimeZone("GMT+8");
        Calendar calendar = Calendar.getInstance(curTimeZone);
        calendar.setTimeInMillis(System.currentTimeMillis());
        calendar.set(Calendar.DAY_OF_MONTH, 0);
//        calendar.set(Calendar.MONTH, 0);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        return calendar.getTimeInMillis() / 1000 + "";
    }

    public static String getEndTimeOfMonth() {
        TimeZone curTimeZone = TimeZone.getTimeZone("GMT+8");
        Calendar calendar = Calendar.getInstance(curTimeZone);
        calendar.setTimeInMillis(System.currentTimeMillis());
        calendar.set(Calendar.DAY_OF_MONTH, 31);
//        calendar.set(Calendar.MONTH, 31);
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        return calendar.getTimeInMillis() / 1000 + "";
    }

    public static String getStartTime4YearMonth(int year, int month) {

        String formatDate = year + "-" + (month - 1) +
                "-" + DateUtils.calculateDaysInMonth((month - 1)) + " 00:00:00";
        return dateToStamp(formatDate, "yyyy-MM-dd HH:mm:ss");
    }

    public static String getEndTime4YearMonth(int year, int month) {

        String formatDate = year + "-" + month +
                "-" + DateUtils.calculateDaysInMonth(month) + " 23:59:59";
        return dateToStamp(formatDate, "yyyy-MM-dd HH:mm:ss");
    }

    /**
     * 验证固话号码
     */
    public static boolean checkTelephone(String telephone) {
        String regexp = "/^400[0-9]{7}/|/^800[0-9]{7}/|^0[0-9]{2,3}-[0-9]{8}|^((13[0-9])|(15[^4])|(18[0-9])|(17[0-8])|(147))\\d{8}$";
        Pattern pattern = Pattern.compile(regexp);
        Matcher matcher = pattern.matcher(telephone);
        return matcher.matches();
    }

    /**
     * 手机号码
     */
    public static boolean isPhoneNum(String str) {
        String regExp = "^((13[0-9])|(15[^4])|(18[0-9])|(17[0-8])|(147))\\d{8}$";
        Pattern p = Pattern.compile(regExp);
        Matcher m = p.matcher(str);
        return m.matches();
    }

    /**
     * 拨打电话
     */
    public static void call(Context context, String phone) {
        Intent intent = new Intent(Intent.ACTION_DIAL);
        Uri data = Uri.parse("tel:" + phone);
        intent.setData(data);
        context.startActivity(intent);
    }

    /**
     * 打开调用地图对话框
     */
    public static void showMapSelView(final Activity activity, final LatLng latLng) {
        BottomSelectionPopup bottomSelectionPopup = new BottomSelectionPopup(activity);
        bottomSelectionPopup.setTx_1Text(activity.getResources().getString(R.string.text_select_map_amap));
        bottomSelectionPopup.setTx_2Text(activity.getResources().getString(R.string.text_select_map_baidu));
        bottomSelectionPopup.setTxCancel(activity.getResources().getString(R.string.btn_cancel));
        bottomSelectionPopup.setOnClickItemListener(new BottomSelectionPopup.OnClicktemListener() {
            @Override
            public void onClickItem(View v) {
                switch (v.getId()) {
                    case R.id.ll_1:
                        if (AMapUtil.isInstallByRead(PACKAGE_NAME_AMAP)) {
                            AMapUtil.goToNaviAmapActivity(activity, "test", null, latLng.latitude + "", latLng.longitude + "", "1", "2");
                        } else {
                            ShowToast.showShortToast(activity.getResources().getString(R.string.text_select_map_install_amap));
                        }
                        break;
                    case R.id.ll_2:
                        if (AMapUtil.isInstallByRead(PACKAGE_NAME_BAIDU)) {
                            LocationEntity locationEntity = SPUtil.getUserLocation();
                            String latitude = locationEntity.getLatitude();
                            String longitude = locationEntity.getLongitude();
                            String cityName = locationEntity.getCityName();
                            AMapUtil.goToNaviBaidumapActivity(activity, latitude, longitude, latLng.latitude + "", latLng.longitude + "", cityName);
                        } else {
                            ShowToast.showShortToast(activity.getResources().getString(R.string.text_select_map_install_baidu));
                        }
                        break;
                }
            }
        });
        bottomSelectionPopup.showPopupWindow();
    }


    public static String getMD5(String content) {
        try {
            MessageDigest digest = MessageDigest.getInstance("MD5");
            //对象把String 转换成字节，再使用MD5转化
            digest.update(content.getBytes());
            return getHashString(digest);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }

    private static String getHashString(MessageDigest digest) {
        StringBuilder builder = new StringBuilder();
        for (byte b : digest.digest()) {
            builder.append(Integer.toHexString((b >> 4) & 0xf));
            builder.append(Integer.toHexString(b & 0xf));
        }
        return builder.toString();
    }

    /**
     * 获取年月日
     */
    public static int[] getDate() {
        Calendar c = Calendar.getInstance();
        int[] date = new int[3];
        date[0] = c.get(Calendar.YEAR);
        date[1] = c.get(Calendar.MONTH) + 1;
        date[2] = c.get(Calendar.DAY_OF_MONTH);
        return date;
    }

    /**
     * 获取年月日
     */
    public static int[] getTime() {
        Calendar c = Calendar.getInstance();
        int[] date = new int[3];
        date[0] = c.get(Calendar.HOUR);
        date[1] = c.get(Calendar.MINUTE) + 1;
        return date;
    }

    // 检查微信是否安装
    public static boolean isWeixinAvilible(Context context) {
        final PackageManager packageManager = context.getPackageManager();// 获取packagemanager
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);// 获取所有已安装程序的包信息
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if (pn.equals("com.tencent.mm")) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 获取assets资源
     */
    public static JSONArray getFromAssets2Json(String fileName, Context context) {
        try {
            InputStreamReader inputReader = new InputStreamReader(context.getResources().getAssets().open(fileName));
            BufferedReader bufReader = new BufferedReader(inputReader);
            String line;
            String Result = "";
            while ((line = bufReader.readLine()) != null)
                Result += line;
            return new JSONArray(Result);
        } catch (Exception e) {
            // e.printStackTrace();
        }
        return null;
    }

    /**
     * 文本复制
     */
    public static void copyText(String content, Context context) {
        // 得到剪贴板管理器
        ClipboardManager cmb = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        cmb.setText(content.trim());
        ShowToast.showShortToast(context.getString(R.string.text_copy_text_success));
    }

    public static void installAPK(Context context, String filePath) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(new File(filePath)), "application/vnd.android.package-archive");
        context.startActivity(intent);
    }

    public static String toHanyuPinyin(String ChineseLanguage) {
        char[] cl_chars = ChineseLanguage.trim().toCharArray();
        String hanyupinyin = "";
        HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
        defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);// 输出拼音全部小写
        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);// 不带声调
        defaultFormat.setVCharType(HanyuPinyinVCharType.WITH_V);
        try {
            for (int i = 0; i < cl_chars.length; i++) {
                if (String.valueOf(cl_chars[i]).matches("[\u4e00-\u9fa5]+")) {// 如果字符是中文,则将中文转为汉语拼音
                    hanyupinyin += PinyinHelper.toHanyuPinyinStringArray(cl_chars[i], defaultFormat)[0];
                } else {// 如果字符不是中文,则不转换
                    hanyupinyin += cl_chars[i];
                }
            }
        } catch (BadHanyuPinyinOutputFormatCombination e) {
            System.out.println("字符不能转成汉语拼音");
        }
        return hanyupinyin;
    }

    public static String getFirstLetter(String ChineseLanguage) {
        char[] cl_chars = ChineseLanguage.trim().toCharArray();
        String hanyupinyin = "";
        HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
        defaultFormat.setCaseType(HanyuPinyinCaseType.UPPERCASE);// 输出拼音全部大写
        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);// 不带声调
        try {
            String str = String.valueOf(cl_chars[0]);
            if (str.matches("[\u4e00-\u9fa5]+")) {// 如果字符是中文,则将中文转为汉语拼音,并取第一个字母
                hanyupinyin = PinyinHelper.toHanyuPinyinStringArray(
                        cl_chars[0], defaultFormat)[0].substring(0, 1);
                ;
            } else if (str.matches("[0-9]+")) {// 如果字符是数字,取数字
                hanyupinyin += cl_chars[0];
            } else if (str.matches("[a-zA-Z]+")) {// 如果字符是字母,取字母

                hanyupinyin += cl_chars[0];
            } else {// 否则不转换

            }
        } catch (BadHanyuPinyinOutputFormatCombination e) {
            System.out.println("字符不能转成汉语拼音");
        }
        return hanyupinyin.toUpperCase();
    }


    /**
     * 大陆手机号码11位数，匹配格式：前三位固定格式+后8位任意数
     * 此方法中前三位格式有：
     * 13+任意数
     * 15+除4的任意数
     * 18+除1和4的任意数
     * 17+除9的任意数
     * 147
     */
    public static boolean isChinaPhoneLegal(String str) {
        String regExp = "^1[34578][0-9]{9}$";
        Pattern p = Pattern.compile(regExp);
        Matcher m = p.matcher(str);
        return m.matches();
    }

    /**
     * 设置bitmap四周白边
     *
     * @param bitmap 原图
     * @return//
     */
    public static Bitmap bg2WhiteBitmap(Bitmap bitmap) {
        int size = bitmap.getWidth() < bitmap.getHeight() ? bitmap.getWidth() : bitmap.getHeight();
        int num = 50;
        int sizebig = size + num;
        // 背图
        Bitmap newBitmap = Bitmap.createBitmap(sizebig, sizebig, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(newBitmap);

        Paint paint = new Paint();

        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        // 生成白色的
        paint.setColor(Color.WHITE);
        canvas.drawBitmap(bitmap, num / 2, num / 2, paint);
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_ATOP));
        // 画正方形的
        canvas.drawRect(0, 0, sizebig, sizebig, paint);
        return newBitmap;
    }
    /**
     * RecyclerView 移动到当前位置，
     *
     * @param manager  设置RecyclerView对应的manager
     * @param n  要跳转的位置
     */
    public static void MoveToPosition(LinearLayoutManager manager, int n) {
        manager.scrollToPositionWithOffset(n, 0);
        manager.setStackFromEnd(true);
    }


    //判断系统是否设置了默认浏览器
    public static boolean hasPreferredApplication(Context context, Intent intent) {
        PackageManager pm = context.getPackageManager();
        ResolveInfo info = pm.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY);
        return !"android".equals(info.activityInfo.packageName);
    }
//如果info.activityInfo.packageName为android,则没有设置,否则,有默认的程序.

}
